<?php
/*
 * 会员管理
 */
namespace King\Controller;
use King\Model\memberModel;
use King\Model\gradeModel;
use King\Model\orderModel;
use Mobile\Model\tmpmsgModel;


class MemberController extends BaseController {
    
    public $memberModel;
    public $gradeModel;
    
    public $grade_arr;
    public $html;
    public $v;
    
    public $kinglist;//皇冠下级列表
    
    public $laiyuan = array(
        "sharelink" => "链接",
        "scanqrcode" => "扫码",
        "scangh" => "扫码关注",
        "subscribe" => "关注",
        "import" => "导入",
        "timeline" => "朋友圈",
        "singlemessage" => "单聊",
        "groupmessage" => "群聊",
        "admin" => "管理员更改"
    );
    
    
    public function __construct() {
        parent::__construct();

		
		
        $this->memberModel = new memberModel();
        $this->gradeModel = new gradeModel();
        $this->orderModel = new orderModel();
        $this->grade_arr = $this->_get_gradename(array(fangan_type=>1));//获取用户等级
        
        $this->assign('grade_arr',$this->grade_arr);
    }
   /*
    * 获取用户等级或聘级
    * $where 是 array  判断是聘级或等级
    */
    protected function _get_gradename($where){
        //$where = array();
        $grade_list = $this->gradeModel->getGradeList($where);
    
        $new_grade = array();
        foreach($grade_list as $k=>$v){
            $new_grade[$v['grade_id']] = $v['grade_name'];
        }
        return $new_grade;
    }
    
    

    protected function _get_member_where(){
        $arrow = array(
            "mobile",
            "nickname",
            "province",
            "groupid",
            "start_create_time",
            "end_create_time",
            "user_id",
            "grade_id",
            "vip"
        );//允许提交的数据
        $data = param_filter($_GET,$arrow,$must=NULL,$filter=true);//过滤数据
        
        $where = "1";
        //todo
        if(is_set($data,'mobile')){
            $where .= " AND mobile like '".$data['mobile']."%'";
        }
        if(is_set($data,'nickname')){
            $where .= " AND ((nickname like'%".$data['nickname']."%') OR (realname like'%".$data['nickname']."%'))";
        }
        if(is_set($data,'province')){
            $where .= " AND province='".$data['province']."'";
        }
        if(is_set($data,'groupid')){
            $where .= " AND groupid='".$data['groupid']."'";
        }
        if(is_set($data,'express')){
            $where .= " AND express='".$data['express']."'";
        }
        if(is_set($data,'user_id')){
            $where .= " AND uid='".$data['user_id']."'";
        }
        if(is_set($data,'grade_id')){
            $where .= " AND grade_id=".$data['grade_id'];
        }
        
        if(is_set($data,'vip')){
            $where .= " AND grade_id>=2";
        }
        
        if(is_set($data,'start_create_time')){
            $where .= " AND create_time>='".$data['start_create_time']."'";
        }
        if(is_set($data,'end_create_time')){
            $where .= " AND create_time<'".trim($data['end_create_time'])."'";
        }
        
        return $where;
    }
    
    /*
     * 计算代理数量,代理消费金额
     */
    protected function _jisuan_daili_count($uid){
        $a_uid = $b_uid = array();//一级代理的uid集合
        $a_daili = $b_daili = $c_daili = array();//集合
        $a_count = $b_count = $c_count = 0;
        
        //计算我的一级代理
        $where_a = array(
            'refer_uid' => $uid
        );
        $a_daili = $this->memberModel->where($where_a)->select();
        $a_count = $this->memberModel->where($where_a)->count();
        
        //计算我的二级代理
        if(!empty($a_daili)){
            foreach ($a_daili as $k=>$v){
                $a_uid[] = $v['uid'];
            }
            //计算二级代理
            $where_b = array(
                'refer_uid' => array(
                    "IN",$a_uid
                )
            );
            $b_daili = $this->memberModel->where($where_b)->select();//我的二级代理
            $b_count = $this->memberModel->where($where_b)->count();
            if(!empty($b_daili)){
                foreach ($b_daili as $kk=>$vv){
                    $b_uid[] = $vv['uid'];
                }
                //计算3级代理
                $where_c = array(
                    'refer_uid' => array(
                        "IN",$b_uid
                    )
                );
                $c_count = $this->memberModel->where($where_c)->count();
            }
        }
        
        $daili_count = array(
            '1' => $a_count,
            '2' => $b_count,
            '3' => $c_count
        );
        
        return $daili_count;
        
    }
    

   
    /*
     * 我的代理
     */
    public function daili(){

        $dj = get('dj',1);//等级
        $uid = get('daili_user_id');
        
        
        $page = get('p',1);
        
        $a_uid = $b_uid = array();//一级代理的uid集合
        $a_daili = $b_daili = $c_daili = array();//集合
        $a_count = $b_count = $c_count = 0;
        
        //计算我的一级代理
        $where_a = array(
            'refer_uid' => $uid
        );
        
        
        $a_count = $this->memberModel->where($where_a)->count();
        if($dj == 1){
            $a_daili = $this->memberModel->getMemberList($where_a,$page);
            $page = new \Think\Page($a_count, 25);//
        }else{
            $a_daili = $this->memberModel->where($where_a)->select();
        }
        
        
        //计算我的二级代理
        if(!empty($a_daili)){
            foreach ($a_daili as $k=>$v){
                $a_uid[] = $v['uid'];
            }
            //计算二级代理
            $where_b = array(
                'refer_uid' => array(
                    "IN",$a_uid
                )
            );
            
            
            $b_count = $this->memberModel->where($where_b)->count();
            if($dj == 2){
                $page = new \Think\Page($b_count, 25);//
                $b_daili = $this->memberModel->getMemberList($where_b,$page);//我的二级代理
            }else{
                $b_daili = $this->memberModel->where($where_b)->select();//我的二级代理
            }
            
            
           
            if(!empty($b_daili)){
                foreach ($b_daili as $kk=>$vv){
                    $b_uid[] = $vv['uid'];
                }
                //计算3级代理
                $where_c = array(
                    'refer_uid' => array(
                        "IN",$b_uid
                    )
                );
                
                
                $c_count = $this->memberModel->where($where_c)->count();
                if($dj == 3){
                    $page = new \Think\Page($c_count, 25);//
                    $c_daili = $this->memberModel->getMemberList($where_c,$page);//我的二级代理
                }else{
                    $c_daili = $this->memberModel->where($where_c)->select();//我的3级代理
                }
                
                
            }
        }
        
        $daili_count = array(
            '1' => $a_count,
            '2' => $b_count,
            '3' => $c_count
        );
        $this->assign('daili_count',$daili_count);
        
        
        if($dj == 1){
            $datalist = $a_daili;
        }else if($dj == 2){
            $datalist = $b_daili;
        }else if($dj == 3){
            $datalist = $c_daili;
        }
        
        
        foreach ($datalist as $k=>$v){
            
            $datalist[$k]['daili_count'] = $this->_jisuan_daili_count($v['uid']);
            $datalist[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
            
            $datalist[$k]['laiyuan'] = $this->laiyuan[$v['regfrom']] ? $this->laiyuan[$v['regfrom']] : "未知";
        }
        
        $this->assign('datalist',$datalist);
       
        
        
        $show = $page->show3();
        $this->assign('page', $show);
        
        $this->display('index');
    }
    
    
    /*
     * 会员列表
     */
    public function index(){
        //根据kinguid 查询所有下级遇到皇冠中断
        $kinguid = $this->kinguid;

        $kinglist = $this->getXiaji($kinguid);
        foreach($kinglist as $k=>$v){
            $kinglist[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
        }
     
        $this->assign('datalist',$kinglist);
        $this->display();
    }
    
    public function getXiaji($uid){
        
        $map = array(
            'refer_uid' => $uid            
        );
        $list = $this->memberModel->where($map)->select();
   
        foreach ($list as $v){
            $this->kinglist[] = $v;
            $this->getXiaji($v['uid']);
        }
       
        return $this->kinglist;
    }
    
    
    public function memberpage(){
        $where = $this->_get_member_where();
        $page = get('p',1);
        
        $all = $this->memberModel->where($where)->count();//总数
        
        $page_num = ceil($all/5000);
        
        return_json(0,"正在努力计算总....",$page_num);

    }
    
    
    public function memberexcel(){
        
        set_time_limit(1000);
        
        $where = $this->_get_member_where();
        $page = get('p',1);
        
        $all = $this->memberModel->where($where)->count();//总数
        
        $page_num = ceil($all/5000);
        
        //计算总
        $member_list = $this->memberModel->where($where)->order('uid DESC')->page($page,5000)->select();
        

        $datastr = "";
        
        if(empty($member_list)){
            return_json(1,"数据为空");
        }
        
        foreach($member_list as $k=>$v){
        
            $member_list[$k]['grade_name'] = $this->_mygrade($v);//获取用户等级
            
            $datastr .= $member_list[$k]['uid'].",";//UID
            
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$member_list[$k]['nickname']).",";//转义
            
            $datastr .= $member_list[$k]['grade_name'].",";//UID
            
            $datastr .= str_replace(array(",","'","\""),array("，","＂","＂"),$member_list[$k]['refer_nickname']).",";//转义
            
            $datastr .= $member_list[$k]['refer_uid'].",";//UID
            
            $datastr .= $member_list[$k]['tixian'].",";//UID
            $datastr .= $member_list[$k]['money'].",";//UID
            $datastr .= $member_list[$k]['score'].",";//UID
            
            $datastr .= $member_list[$k]['cash_money']."\n";//UID
            
            
        }

        //$member_count = $this->memberModel->getMemberCount($where);
  //      $header = "用户ID,昵称,等级,上级昵称,上级ID,1级数量,2级数量,3级数量,消费金额,销售金额,已提佣金,可提佣金,微币,剩余支持面膜,是否关注,加入时间,来源\n";
        $header = "用户ID,昵称,等级,上级昵称,上级ID,已提佣金,可提佣金,积分,钱包余额\n";
        
        
        $this->excel($datastr,$header,$excel_name="第".$page."页-共".$page_num."页-用户信息-");
    }
    
    
    /*
     * 级别列表
     */
    public function grade(){
        
        $where = array();
        $grade_list = $this->gradeModel->getGradeList($where);
        $this->assign('datalist',$grade_list);
        
        $this->display();
    }
    
    /*
     * 会员等级
     */
    protected function _mygrade($userinfo){

        $grade = $this->grade_arr[$userinfo['grade_id']];

        return $grade;
    }
    
    /*
     * changelog 
     * 会员信息变更，重要操作日志
     */
    public function changelog(){
        

        $page = get("p",1);
        $type = 0;
        if($_GET["type"]){
            $where = array(
                "log_type" => $_GET["type"]
            );
            $type = $_GET["type"];
        }
        $c = M("actionlog");
        $logs = $c->where($where)->limit(($page-1)*100,100)->order("create_time desc")->select();
        $count = $c->count();
        $this->assign('count',$count);
        
        $page = new \Think\Page($count, 100);
        $show = $page->show3();
        $this->assign('page', $show);
        $this->assign("logs",$logs);
        $this->assign('type', $type);
        $this->display();
    }
	


    
    
    public function memberweb(){
            
       $kinguid = $this->kinguid;
       $list = $this->treeXiaji($kinguid);
       foreach ($list as $k=>$v){
           $new[$v['id']] = $v;
       }
       
       $new[$this->kinguid] = $this->memberModel->where("uid = '".$kinguid."'")->field('uid as id,refer_uid as pid,realname as name,grade_id')->find();
       $new[$this->kinguid]['pid'] = 0;
       $xiaji = genTree5($new);
       $html = $this->_handleHtml($xiaji);
       $html = "<ul>".$html;
       $html.= "</ul>";
       $this->assign("html",$html);
       $this->display();
        
        
    }
    
    public function treeXiaji($uid){
    
        $map = array(
            'refer_uid' => $uid
        );
    
        $list = $this->memberModel->where($map)->getField('uid as id,refer_uid as pid,realname as name,grade_id');
         
    
        foreach ($list as $v){

            $this->kinglist[] = $v;
            $this->treeXiaji($v['id']);
        }
         
        return $this->kinglist;
    }
    
    

    
    /*
     * 取出某个人的数据
     * 
     */
    protected function _getXiaJiByUid($uid,$xiaji){

        foreach ($xiaji as $k=>$v){

            if($k == $uid){
               
                $this->v = array($uid=>$v);
               
            }
            
            //递归查找
            if($v['son']){
                   $this->_getXiaJiByUid($uid,$v['son']);
            }
        }
        return $this->v;
    }
    
    
    /*
     * 组装html
     */
    protected function _handleHtml($arr){
        
        foreach ($arr as $k=>$v){
          $grade = $this->grade_arr[$v['grade_id']];
          if($v['son']){
              $this->html .= "<li><span><i class='icon-minus-sign'></i>".$v['name'].'-'.$v['id'].'-'.$grade."</span><ul> ";
              $this->_handleHtml($v['son']);
              
          }else{
              $this->html .= "<li><span><i class='icon-leaf'></i>".$v['name'].'-'.$v['id'].'-'.$grade."</span></li>";
          }
        }
        $this->html .= "</ul></li>";
        return ($this->html);
    }
 
    
    /*
     * 模板消息
     * 手工调整升级
     */
    
    /*
     * 升级用户等级
     */
    protected function _shengji($userinfo,$old,$new){
    
        //升级member表用户等级
        $where = array(
            "uid" => $userinfo['uid']
        );
        $data = array(
            "grade_id" => $new,//更改等级2
        );
        $res = $this->memberModel->editMember($where, $data);
    
        //发送模板消息
        $this->_shengjiMsg($userinfo,$old,$new);
    
    }
    
    
    /*
     * 升级通知,模板消息
     *
     */
    protected function _shengjiMsg($userinfo,$old,$new){
    
        //发送升级模板消息
        //判断是否关注, 没关注就别发了
        if(!$userinfo['subscribe']){
            //return false;
            //TODO
        }
    
        //发送模板消息
        $msg = $this->_sendsjmsgtmp($userinfo,$old,$new);//拼接模板消息
    
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => $msg,
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
    
        return true;
    }
    
    
    /*
     * 升级消息
     *
     */
    protected function _sendsjmsgtmp($userinfo,$old,$new){
    
        $grade_arr = $this->_get_gradename();
    
        $tmp_id = $this->tmpl['DENG_JI']['tmp_id'];
        $color = $this->tmpl['DENG_JI']['color'];
    
        $url = get_domain()."/mobile/user/grade/";
        $footer ='\\n'."点击查看详情...";
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,//
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode("恭喜,你的等级已提升~".'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($grade_arr[$old]),//原先等级
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($grade_arr[$new]),//new等级
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
    
        return $msg = urldecode(json_encode($msg));
    }
    

    


}